/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Funcionario;

import Controle.Controlador;
import Modelo.Cliente;
import Visao.Funcionario.Pedido.SelecionarClientePedido;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

/**
 *
 * @author Eder
 */
public class InserirAlterarCliente extends javax.swing.JFrame {

    boolean update = false;
    Integer codigoClienteUpdate;
    GerenciarClientes gerenciar;
    SelecionarClientePedido clientePedido;
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Calendar a;

    /**
     * Creates new form InserirAlterarCliente
     */
    public InserirAlterarCliente() {
        initComponents();
    }

    public InserirAlterarCliente(GerenciarClientes gerenciar) {
        initComponents();
        this.gerenciar = gerenciar;

    }
    
    
    public InserirAlterarCliente(SelecionarClientePedido clientePedido) {
        initComponents();
        this.clientePedido = clientePedido;

    }

    public InserirAlterarCliente(GerenciarClientes gerenciar, int codigo) {
        initComponents();
        this.gerenciar = gerenciar;
        this.update = true;
        this.codigoClienteUpdate = codigo;
        setDadosVisao(Controlador.convertModeloClienteToDadosVisao(codigo));
    }
    
    public InserirAlterarCliente(SelecionarClientePedido clientePedido, int codigo) {
        initComponents();
        this.clientePedido = clientePedido;
        this.update = true;
        this.codigoClienteUpdate = codigo;
        setDadosVisao(Controlador.convertModeloClienteToDadosVisao(codigo));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jCancelarB = new javax.swing.JButton();
        jtfComp = new javax.swing.JTextField();
        jConcluirB = new javax.swing.JButton();
        jftRua = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jtfNome = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jtftel_1 = new javax.swing.JFormattedTextField();
        jftfRg = new javax.swing.JFormattedTextField();
        jtfDataNasc = new javax.swing.JFormattedTextField();
        jLabel10 = new javax.swing.JLabel();
        jtftel_2 = new javax.swing.JFormattedTextField();
        jtfNum = new javax.swing.JFormattedTextField();
        jcbBairro = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jcbSexo = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Inserir Cliente");

        jCancelarB.setText("Cancelar");
        jCancelarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCancelarBActionPerformed(evt);
            }
        });

        jtfComp.setPreferredSize(new java.awt.Dimension(308, 20));

        jConcluirB.setText("OK");
        jConcluirB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jConcluirBActionPerformed(evt);
            }
        });

        jftRua.setPreferredSize(new java.awt.Dimension(196, 20));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Tel_1:*");

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel9.setText("Bairro:*");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Nome:*");

        jtfNome.setPreferredSize(new java.awt.Dimension(308, 20));
        jtfNome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfNomeActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("Data Nasc:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("Comp:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setText("Nº:*");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Rua:*");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel7.setText("RG:");

        try {
            jtftel_1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("## ####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtftel_1.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtftel_1.setPreferredSize(new java.awt.Dimension(110, 20));

        try {
            jftfRg.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftfRg.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jftfRg.setPreferredSize(new java.awt.Dimension(110, 20));

        try {
            jtfDataNasc.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtfDataNasc.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtfDataNasc.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtfDataNasc.setPreferredSize(new java.awt.Dimension(110, 20));

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel10.setText("Tel_2:");

        try {
            jtftel_2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("## ####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtftel_2.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtftel_2.setPreferredSize(new java.awt.Dimension(110, 20));

        try {
            jtfNum.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtfNum.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtfNum.setPreferredSize(new java.awt.Dimension(86, 20));

        jcbBairro.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Alto Alegre", "Brasília", "Brazmadeira", "Canadá", "Cancelli", "Cascavel Velho", "Cataratas", "Centro", "Coqueiral", "Country", "Esmeralda", "Floresta", "Guarujá", "Interlagos", "Maria Luiza", "Morumbi", "Neva", "Pacaembu", "Parque São Paulo", "Parque Verde", "Periolo", "Pioneiros Catarinenses", "Recanto Tropical", "Região do Lago", "Santa Cruz", "Santa Felicidade", "Santo Onofre", "Santos Dumont", "São Cristóvão", "Universitário", "XIV De Novembro" }));
        jcbBairro.setMinimumSize(new java.awt.Dimension(20, 20));
        jcbBairro.setName("");
        jcbBairro.setPreferredSize(new java.awt.Dimension(110, 20));
        jcbBairro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbBairroActionPerformed(evt);
            }
        });

        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel8.setIcon(new javax.swing.ImageIcon("C:\\Users\\Andre Luiz\\Desktop\\solucoes-motivos-cliente.gif")); // NOI18N
        jLabel8.setToolTipText("");
        jLabel8.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jLabel8.setVerticalTextPosition(javax.swing.SwingConstants.TOP);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel11.setText("Sexo:*");

        jcbSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione o Sexo", "MASCULINO", "FEMININO" }));
        jcbSexo.setPreferredSize(new java.awt.Dimension(110, 20));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel2))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel11)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                            .addComponent(jLabel9)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jcbBairro, 0, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jftRua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jtfNum, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(144, 144, 144)
                        .addComponent(jCancelarB, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(jConcluirB, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jtfComp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtfNome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jtftel_1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jftfRg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel10))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jtfDataNasc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jtftel_2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(11, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jtfNome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jtfDataNasc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jftfRg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtftel_2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel10)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jtftel_1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(jcbBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jftRua, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jtfNum, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfComp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCancelarB, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jConcluirB, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(71, 71, 71))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jcbBairro, jcbSexo});

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-544)/2, (screenSize.height-338)/2, 544, 338);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Captura todos os dados da tela Cadastro de cliente e passando as
     * informações para um objeto do tipo Cliente. Por fim a função retorna o
     * objeto.
     *
     * @return Cliente
     */
    public ArrayList<String> getDadosVisao() {
        ArrayList<String> cliente = new ArrayList();
        Matcher numeros;

        cliente.add("" + codigoClienteUpdate);
        cliente.add(jtfNome.getText().toUpperCase());
        cliente.add(jftfRg.getText());
        cliente.add(jtfDataNasc.getText());
        cliente.add(jcbSexo.getSelectedItem().toString());
        numeros = Pattern.compile("[0-9]").matcher(jtftel_1.getText());
        if (numeros.find()) {
            cliente.add(jtftel_1.getText());
        } else {
            cliente.add("");
        }
        numeros = Pattern.compile("[0-9]").matcher(jtftel_2.getText());
        if (numeros.find()) {
            cliente.add(jtftel_2.getText());
        } else {
            cliente.add("");
        }
        cliente.add("");
        cliente.add(jcbBairro.getSelectedItem().toString());
        cliente.add(jftRua.getText().toUpperCase());
        cliente.add(jtfNum.getText().replace(" ", ""));
        cliente.add(jtfComp.getText().toUpperCase());

        //System.out.println("size: "+cliente.size());

        return cliente;
    }

    private void setDadosVisao(ArrayList<String> param) {
        try {
            //System.out.println(param.toString());
            jtfNome.setText(param.get(1));
            jftfRg.setText(param.get(2));
            jtfDataNasc.setText(param.get(3));
            jcbSexo.setSelectedItem(param.get(4));
            jtftel_1.setText(param.get(5));
            jtftel_2.setText(param.get(6));
            jcbBairro.setSelectedItem(param.get(8));
            jftRua.setText(param.get(9));
            System.out.println("num: " + param.get(10));
            jtfNum.setText(param.get(10).replace(" ", ""));
            jtfComp.setText(param.get(11));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, "Erro ao Setar dados do Cliente na tela", "Erro!", 0);
        }

    }

    private void validarEntradaDados() throws Exception {
        //jcbCategoria jtaIngredientes jtfSabor
        Matcher letras = Pattern.compile("[a-zA-Z]").matcher(jtfNome.getText());
        Matcher numeros = Pattern.compile("[0-9]").matcher(jtfNome.getText());
        Matcher espaco;

        if (jtfNome.getText().length() == 0) {
            throw new Exception("Digite um nome para o Cliente");
        }
        if (!letras.find() || numeros.find()) {
            throw new Exception("O nome do Cliente é inválido\nO nome do cliente devera conter pelo menos um letra\ne não poderá conter números.  ");
        }

        if (!"  /  /    ".equals(jtfDataNasc.getText())) {
            try {
                Date data = DateFormat.getDateInstance().parse(jtfDataNasc.getText());
                validarData(jtfDataNasc.getText(), true);
//                dateFormat.setLenient(false);
//                dateFormat.format(data);
            } catch (Exception ex) {
                throw new Exception("A data de nascimento do Cliente é inválida\n" + ex.getMessage() + "\nA data de nascimento deve seguir o seguinte formato: dd/mm/aaaa .");
            }
        }
        
        numeros = Pattern.compile("[0-9]").matcher(jtftel_1.getText());
        espaco = Pattern.compile(" ").matcher(jtftel_1.getText());
        if (!numeros.find()) {
            throw new Exception("Informe o numero do Telefone do Cliente");
        }
        if (numeros.find() && espaco.find(5)) {
            throw new Exception("O numero do telefone 1 do Cliente é inválido\nO telefone do cliente deve seguir o seguinte formato: (##) ####-#### .  ");
        }

        numeros = Pattern.compile("[0-9]").matcher(jtftel_2.getText());
        espaco = Pattern.compile(" ").matcher(jtftel_2.getText());
        if (numeros.find() && espaco.find(5)) {
            throw new Exception("O numero do telefone 2 do Cliente é inválido\nO telefone do cliente deve seguir o seguinte formato: (##) ####-#### .  ");
        }
        if (jcbSexo.getSelectedIndex() == 0) {
            throw new Exception("Informe o Sexo do Cliente.");
        }
        if (jcbBairro.getSelectedIndex() == 0) {
            throw new Exception("Informe o Bairro do Cliente.");
        }
        letras = Pattern.compile("[a-zA-Z]").matcher(jftRua.getText());
        if (!letras.find()) {
            throw new Exception("Informe a rua do Cliente.");
        }
        numeros = Pattern.compile("[0-9]").matcher(jtfNum.getText());
        if(!numeros.find()) {
            throw new Exception("Informe o numero do Endereço do Cliente.");
        }
    }

    /**
     * Metodo para a Validação de Datas
     * @param data  String contendo a data para validação
     * @param permitir_data_posteriores_dataAtual Boolean para permitir ou não datas posteriores a data atual do sistema
     * @throws Exception 
     */
    public void validarData(String data, boolean permitir_data_posteriores_dataAtual) throws Exception {

        if (data == null) {
            throw new Exception("Não há Data para validar");
        }

        int dia = Integer.parseInt(data.substring(0, 2));
        int mes = Integer.parseInt(data.substring(3, 5));
        int ano = Integer.parseInt(data.substring(6, 10));

        if (mes < 1 || mes > 12) {
            throw new Exception("Mês Inválido!");
        }


        if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 12) {
            if (dia < 1 || dia > 31) {
                throw new Exception("Dia Inválido!");
            }

        } else if (mes == 4 || mes == 6 || mes == 9 || mes == 10 || mes == 11) {
            if (dia < 1 || dia > 30) {
                throw new Exception("Dia Inválido!");
            }
        } else if (mes == 2) {
            if (dia < 1 || dia > 29) {
                throw new Exception("Dia Inválido!");
            }
        }
        
        if (permitir_data_posteriores_dataAtual) {
            String dataAtual = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date(System.currentTimeMillis()));
            //System.out.println("data atual: "+dataAtual);
            int diaAtual = Integer.parseInt(dataAtual.substring(0, 2));
            int mesAtual = Integer.parseInt(dataAtual.substring(3, 5));
            int anoAtual = Integer.parseInt(dataAtual.substring(6, 10));
            
            if(ano>anoAtual)
                throw new Exception("Data posterior a Data atual do Sistema");
            if(ano==anoAtual && mes>mesAtual)
                throw new Exception("Data posterior a Data atual do Sistema");
            if(ano==anoAtual && mes==mesAtual && dia>diaAtual)
                throw new Exception("Data posterior a Data atual do Sistema");
        }
    }

    private void jtfNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfNomeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtfNomeActionPerformed

    private void jcbBairroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbBairroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jcbBairroActionPerformed

    private void jConcluirBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jConcluirBActionPerformed
        // Botão Concluir
        if (!update) {
            try {
                validarEntradaDados();

                if (Controlador.salvar_Cliente(getDadosVisao())) {
                    this.setVisible(false);
                    if(gerenciar!=null){
                        gerenciar.atualizaTabela();
                    }
                    else{
                        clientePedido.atualizaTabela();
                    }
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), "Erro!", 0);
            }
        } else {
            try {
                validarEntradaDados();

                if (Controlador.editar_Cliente(getDadosVisao())) {
                    this.setVisible(false);
                    if(gerenciar!=null){
                        gerenciar.atualizaTabela();
                    }
                    else{
                        clientePedido.atualizaTabela();
                    }
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), "Erro!", 0);
            }
        }
    }//GEN-LAST:event_jConcluirBActionPerformed

    private void jCancelarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCancelarBActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_jCancelarBActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jCancelarB;
    private javax.swing.JButton jConcluirB;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JComboBox jcbBairro;
    private javax.swing.JComboBox jcbSexo;
    private javax.swing.JTextField jftRua;
    private javax.swing.JFormattedTextField jftfRg;
    private javax.swing.JTextField jtfComp;
    private javax.swing.JFormattedTextField jtfDataNasc;
    private javax.swing.JTextField jtfNome;
    private javax.swing.JFormattedTextField jtfNum;
    private javax.swing.JFormattedTextField jtftel_1;
    private javax.swing.JFormattedTextField jtftel_2;
    // End of variables declaration//GEN-END:variables
}
